<?php defined('SYSPATH') OR die('No direct access allowed.');

class Category_Controller extends Forum_Controller {

    public function __construct() {
      parent::__construct();
      $this->template->set_global('basic_href', Router::uri('forum', array('controller'=>'category'))."/");
    }

    public function index() {
			// по умолчанию показывается форум целиком (т.е. ветки без родителей)
      $categories = ORM_MPTT::factory('forum_category')
			->where('parent_id', NULL)
			->find_all() OR $categories = array();
			$arr = array();
			foreach($categories as $category)
			  $arr[$category->title] = $category;
      $this->template->content = View::factory('forum/show_categories')
        ->bind('categories', $categories);
      $this->template->nav->breadcrumb = array();
			$this->template->head['title'] = Kohana::lang('forum.main_page_title');
      $this->template->title = Kohana::lang('forum.main_page_title');
			Event::run('forum.show.root');
    }

    public function __call($method, $args) {
      if (!ctype_digit($method)) {
        Event::run('system.404');
      }
			else $this->category($method);
    }

    public function category($id = NULL) {
			// если форум не указан, надо показать список форумов
			if (is_null($id)) return $this->index();
			$category = ORM_MPTT::factory('forum_category', $id);
			if (!$category->loaded) {
				Event::run('system.404');
			}
      $content = new View('forum/show_category');
			$this->template->set_global('category', $category->as_array());
			$this->template->nav->breadcrumb = $category->parents;
			$page_num = $this->input->get('page', 1);
			$per_page = intval(Kohana::config('forum.post_per_page'));
			$offset = ($page_num - 1)*$per_page;
			$content->posts = $category->limit($per_page, $offset)->forum_posts;
			$pages = Pagination::factory(array
			(
				'style' => Kohana::config('forum.pagination_style'),
				'items_per_page' => $per_page,
				'query_string' => 'page',
				'total_items' => $category->count_last_query()
			));
			$content->subcategories = $category->children;
			$content->pages = $pages;
			$this->template->head['title'] = text::limit_chars($category->title, 16, NULL, TRUE);
			$this->template->content = $content;
			Event::run('forum.show.category', $category);
    }

}
